import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:play_lab/constants/my_strings.dart';
import 'package:play_lab/core/route/route.dart';
import 'package:play_lab/core/utils/dimensions.dart';
import 'package:play_lab/data/controller/request/request_controller.dart';
import 'package:play_lab/data/repo/request/request_repo.dart';
import 'package:play_lab/data/services/api_service.dart';
import 'package:play_lab/view/components/app_bar/custom_appbar.dart';
import 'package:play_lab/core/utils/my_color.dart';
import 'package:play_lab/core/utils/styles.dart';
import 'package:play_lab/view/components/custom_loader/custom_loader.dart';
import 'package:play_lab/view/components/image/my_image_widget.dart';
import 'package:play_lab/view/components/no_data_widget.dart';

class AllRequestScreen extends StatefulWidget {
  const AllRequestScreen({super.key});

  @override
  State<AllRequestScreen> createState() => _AllRequestScreenState();
}

class _AllRequestScreenState extends State<AllRequestScreen> {
  ScrollController scrollController = ScrollController();

  fetchData() {
    Get.find<RequestController>().myRequestList();
  }

  void _scrollListener() {
    if (scrollController.position.pixels == scrollController.position.maxScrollExtent) {
      fetchData();
    }
  }

  @override
  void initState() {
    Get.put(ApiClient(sharedPreferences: Get.find()));
    Get.put(RequestRepo(apiClient: Get.find()));
    final controller = Get.put(RequestController(repo: Get.find()));

    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.allRequestList();
      scrollController.addListener(_scrollListener);
    });
  }

  @override
  void dispose() {
    scrollController.dispose();
    Get.find<RequestController>().clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyColor.colorBlack,
      appBar: CustomAppBar(
        title: MyStrings.allRequested,
        actions: [
          IconButton(
            onPressed: () {
              Get.find<RequestController>().clear();
              Get.toNamed(RouteHelper.myRequestScreen);
            },
            icon: Text(MyStrings.myRequest, style: regularDefault.copyWith(color: MyColor.colorWhite)),
          ),
          SizedBox(width: 20)
        ],
      ),
      body: Padding(
        padding: Dimensions.screenPaddingHV,
        child: GetBuilder<RequestController>(
          builder: (controller) {
            if (controller.isLoading) return CustomLoader();
            if (controller.allRequests.isEmpty && !controller.isLoading) {
              return NoDataFoundScreen(message: MyStrings.noItemRequestedYet);
            }
            return ListView.separated(
              controller: scrollController,
              separatorBuilder: (context, index) => SizedBox(height: Dimensions.space15),
              itemCount: controller.allRequests.length + 1,
              itemBuilder: (context, index) {
                if (index == controller.allRequests.length) {
                  return Center(
                    child: controller.hasNext() ? const CircularProgressIndicator(color: MyColor.primaryColor) : const SizedBox(),
                  );
                }
                final item = controller.allRequests[index];
                return Container(
                  padding: EdgeInsets.all(Dimensions.space10),
                  decoration: BoxDecoration(
                    color: MyColor.cardBg,
                    borderRadius: BorderRadius.circular(Dimensions.mediumRadius),
                  ),
                  child: Column(
                    children: [
                      Row(
                        spacing: Dimensions.space10,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          MyImageWidget(
                            imageUrl: "${controller.imagePath}${item.imagePath}",
                            height: 180,
                            width: 120,
                          ),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Text(
                                  item.item ?? "",
                                  style: boldDefault.copyWith(),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                SizedBox(height: Dimensions.space5),
                                Text(
                                  item.overview ?? "",
                                  style: mulishLight.copyWith(color: MyColor.primaryText2),
                                  maxLines: 5,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                // SizedBox(height: Dimensions.space20),
                                // Align(
                                //   alignment: Alignment.centerRight,
                                //   child: Container(
                                //     padding: EdgeInsets.symmetric(horizontal: Dimensions.space10),
                                //     decoration: BoxDecoration(color: MyColor.pendingColor, borderRadius: BorderRadius.circular(Dimensions.cardRadius)),
                                //     child: Text("Pending", style: mulishMedium.copyWith()),
                                //   ),
                                // ),
                              ],
                            ),
                          )
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(child: Container()),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: Dimensions.space20, vertical: Dimensions.space8),
                            decoration: BoxDecoration(
                              color: MyColor.colorBlack,
                              borderRadius: BorderRadius.circular(Dimensions.extraRadius),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              spacing: Dimensions.space10,
                              children: [
                                iconWIdget(
                                  text: item.upVotes ?? "0",
                                  icon: Icons.thumb_up_outlined,
                                  onTap: () => controller.vote(index),
                                ),
                                iconWIdget(
                                  text: item.downVotes ?? "0",
                                  icon: Icons.thumb_down_outlined,
                                  onTap: () => controller.vote(index, isUpVote: false),
                                ),
                                iconWIdget(
                                  text: "",
                                  icon: item.userSubscribe == "true" ? Icons.notifications : Icons.notifications_outlined,
                                  onTap: () => controller.subscribe(index),
                                ),
                              ],
                            ),
                          ),
                        ],
                      )
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  Widget iconWIdget({
    required String text,
    required IconData icon,
    required VoidCallback onTap,
  }) =>
      InkWell(onTap: onTap, customBorder: CircleBorder(), child: Row(children: [Text(text), SizedBox(width: Dimensions.space5), Icon(icon)]));
}
